package com.hong;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Author csh
 * @Description:java语言操作Zk
 *
 * @Date 2018/9/10 22:38
 */
public class Test001 {
    //zk连接地址
    private static final String CONNECTSTRING="127.0.0.1:2181";
    //zk会话超时时间
    private static final int SESSION_OUTTIME = 2000;
//  使用countDownLatch 阻塞用户程序,用户必须等待连接,发送成功信号
    private static final CountDownLatch countDownLatch = new CountDownLatch(1);


    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        ZooKeeper zooKeeper = new ZooKeeper(CONNECTSTRING, SESSION_OUTTIME, new Watcher() {
//            事件通知
            public void process(WatchedEvent watchedEvent) {
//                    1.获取事件状态
                Event.KeeperState keeperState = watchedEvent.getState();
                //2.判断为连接状态
                if(Event.KeeperState.SyncConnected==keeperState){
//                    3.获取事件类型
                    Event.EventType type = watchedEvent.getType();
                    if(type==Event.EventType.None){
                        countDownLatch.countDown();
                        System.out.println("ZK开始启动连接....###");
                    }
                }
            }
        });
//        阻塞
        countDownLatch.await();
//        创建持久类型 节点开放
//        String result = zooKeeper.create("/hong99", "lasting".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        String result = zooKeeper.create("/hong999", "lasting".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        System.out.println("####新增节点信息"+result);
        Thread.sleep(5000);
        zooKeeper.close();
    }
}
